//
//  XGStatusViewModel.swift
//  TodayNews
//
//  Created by monkey on 2020/2/22.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import YYText
import SwiftyJSON
import HandyJSON

/// 配图外部间距
public let kPicturesViewOuterMargin:CGFloat = 10
/// 配图内部间距
public let kPicturesViewInnerMargin:CGFloat = TodayNews_Screen_Scale
/// 配图视图列数
public let kPicturesViewColumns:Int = 3
/// 单个图片宽高
public let kPicturesViewItemWidth:CGFloat = floor(((TodayNews_Screen_Width - 2 * kPicturesViewOuterMargin) - CGFloat(kPicturesViewColumns - 1) * kPicturesViewInnerMargin) / CGFloat(kPicturesViewColumns))

class XGStatusViewModel
{
    /// 用户名
    var userName: String? {
        return statusModel.user?.screen_name
    }
    var userIcon: String? {
        return statusModel.user?.avatar_url
    }
    /// 缩略图数组
    var thumbImageList: [XGImageInfo]? {
        switch statusModel.item_type {
        case .commentOrQuoteContent,.commentOrQuoteOthers:
            return statusModel.origin_thread?.thumb_image_list
        default:
            return statusModel.thumb_image_list
        }
    }
    /// 大图数组
    var largeImagelist: [XGImageInfo]? {
        switch statusModel.item_type {
        case .commentOrQuoteContent,.commentOrQuoteOthers:
            return statusModel.origin_thread?.large_image_list
        default:
            return statusModel.large_image_list
        }
    }
    /// cell类型
    var itemType: XGStatusType {
        return statusModel.item_type
    }
    /// 文章/视频标题
    var articleOrVideoTitle: String? {
        return statusModel.group?.title
    }
    /// 文章/视频图片
    var articleOrVideoThumbUrl: String? {
        return statusModel.group?.thumb_url
    }
    /// 动态类型
    var statusType: XGStatusType {
        return statusModel.item_type
    }
    /// 媒体类型
    var mediaType: XGStatusGroupMediaType {
        return statusModel.group?.media_type ?? .postArticle
    }
    /// 是否认证
    var isUserVerified: Bool {
        return statusModel.user?.user_verified ?? false
    }
    /// 是否引用其他内容
    var isReferenceOther: Bool {
        return statusModel.item_type == .commentOrQuoteContent
    }
    /// 引用的用户信息
    var originalUserInfo: XGUserInfo? {
        return statusModel.origin_thread?.user
    }
    /// 内容属性文本
    private(set) var contentAttributedString: NSAttributedString
    /// 转发动态属性文本
    private(set) var referenceContentAttributedString: NSAttributedString?
    /// 评论数
    private(set) var commentCount: String
    /// 点赞数
    private(set) var diggCount: String
    /// 转发数
    private(set) var forwardCount: String
    /// 创建时间
    private(set) var createTime: String
    /// 配图视图尺寸
    private(set) var picturesViewSize: CGSize = CGSize.zero
    /// 行高
    private(set) var rowHeight: CGFloat = 0
    /// 动态详情头部视图高度
    private(set) var headerViewHeight: CGFloat = 0
    /// 动态评论
    private(set) var statusComments = [XGStatusCommentViewModel]()
    /// 是否有更多评论
    private(set) var isHasMoreComments: Bool = false
    /// 动态模型
    private let statusModel: XGStatusModel
    /// 动态评论偏移量
    private var commentOffset: Int = 0
    
    init(statusModel: XGStatusModel)
    {
        commentCount = statusModel.comment_count.countString
        diggCount = statusModel.digg_count.countString
        forwardCount = statusModel.forward_count.countString
        createTime = Date.convertToCreateString(sinceNow: TimeInterval(statusModel.create_time))
        
        // 计算cell行高
        let thumbImageList = (statusModel.item_type == .commentOrQuoteContent
        || statusModel.item_type == .commentOrQuoteOthers) ? statusModel.origin_thread?.thumb_image_list : statusModel.thumb_image_list
        if thumbImageList != nil { // 有图片
            var picturesViewWidth: CGFloat = 0
            var picturesViewHeight: CGFloat = 0
            switch thumbImageList!.count {
            case 1:
                // 等比例缩放
                let imageInfo = thumbImageList![0]
                let imageWidth = CGFloat(imageInfo.width)
                let imageHeight = CGFloat(imageInfo.height)
                picturesViewWidth = TodayNews_Screen_Width
                picturesViewHeight = floor(TodayNews_Screen_Width / imageWidth * imageHeight) + kPicturesViewOuterMargin
            case 2...9:
                picturesViewWidth = TodayNews_Screen_Width
                let rows = (thumbImageList!.count - 1) / kPicturesViewColumns + 1
                picturesViewHeight = CGFloat(rows) * kPicturesViewItemWidth + CGFloat(rows - 1) * kPicturesViewInnerMargin + kPicturesViewOuterMargin
            default:
                picturesViewWidth = 0
                picturesViewHeight = 0
            }
            picturesViewSize = CGSize(width: picturesViewWidth, height: picturesViewHeight)
        }
        
        rowHeight += 5 + 5 + 40 // 头像
        // 正文
        contentAttributedString = XGEmojiManager.shared.convertToAttributeString(contnet: statusModel.content ?? "", fontSize: 15, textColor: UIColor.darkGray)
        let contentHeight = XGCalculator.calculateAttributeString(text: contentAttributedString, width: TodayNews_Screen_Width - 20, maxHeight: 150.0)
        rowHeight += 10 + contentHeight
        switch statusModel.item_type {
        case .postContent,.postSmallVideo: // 发布内容 发布小视频
            rowHeight += picturesViewSize.height
        case .commentOrQuoteContent, .commentOrQuoteOthers: // 引用其他用户的动态
            rowHeight += picturesViewSize.height
            rowHeight += 10 + 5 + 30 // 引用用户视图
            if let refenerceContent = statusModel.origin_thread?.content { // 引用文本
                referenceContentAttributedString = XGEmojiManager.shared.convertToAttributeString(contnet: refenerceContent, fontSize: 15, textColor: UIColor.darkGray)
                let referenceContentHeight = XGCalculator.calculateAttributeString(text: referenceContentAttributedString!, width: TodayNews_Screen_Width - 20, maxHeight: 150.0)
                rowHeight += 10 + referenceContentHeight
            }
        case .postArticleOrVideo,.answerQuestion,.proposeQuestion: // 发布文章 提出问题 回答问题
            rowHeight += 10 + kStatusArticleViewHeight
        default:
            break
        }
        rowHeight += 10 + 44 // 底部工具栏
        rowHeight = ceil(rowHeight)
        
        // 计算动态详情头部视图高度
        headerViewHeight += 5 + 40 // 头像
        // 正文
        headerViewHeight += 10 + XGCalculator.calculateAttributeString(text: contentAttributedString, width: TodayNews_Screen_Width - 20)
        switch statusModel.item_type {
        case .postContent:
            headerViewHeight += picturesViewSize.height
        case .commentOrQuoteContent, .commentOrQuoteOthers: // 引用其他用户的动态
            headerViewHeight += picturesViewSize.height
            headerViewHeight += 10 + 5 + 30 // 引用用户视图
            if let referenceContentAttributedString = referenceContentAttributedString { // 引用文本
                headerViewHeight += 10 + XGCalculator.calculateAttributeString(text: referenceContentAttributedString, width: TodayNews_Screen_Width - 20)
            }
        default:
            break
        }
        headerViewHeight = 10 + ceil(headerViewHeight)
        
        self.statusModel = statusModel
    }
}

// MARK: - 网络扩展

extension XGStatusViewModel
{    
    /// 加载动态评论数据
    /// - Parameter completionHandle: 完成回调
    func fetchStatusComments(completionHandle: @escaping(Bool,Bool) -> Void) -> Void
    {
        switch statusModel.item_type {
        case .commentOrQuoteContent,.commentOrQuoteOthers: // 引用
            AlamofireTool.loadReferenceStatusCommentData(statusId: statusModel.id, offset: commentOffset) { (responseObject, error) in
                if responseObject == nil || error != nil {
                    XGPrint("加载动态评论数据失败!")
                    completionHandle(false,false)
                    return
                }
                
                let jsonObject = JSON(responseObject!)
                let data = jsonObject["data"].dictionary
                let hasMore = data?["has_more"]?.bool ?? false
                let commentModels = data?["data"]?.array?.compactMap({ return XGStatusCommentModel.deserialize(from: $0.dictionaryObject)}) ?? []
                self.isHasMoreComments = hasMore
                self.commentOffset = data?["offset"]?.int ?? 0
                self.statusComments += commentModels.map({ return XGStatusCommentViewModel(statusCommentModel: $0)})
                completionHandle(true,hasMore)
            }
        default:
            AlamofireTool.loadUserStatusCommentData(statusId: statusModel.id, offset: commentOffset) { (responseObject, error) in
                if responseObject == nil || error != nil {
                    XGPrint("加载动态评论数据失败!")
                    completionHandle(false,false)
                    return
                }
                
                let jsonObject = JSON(responseObject!)
                let hasMore = jsonObject["has_more"].bool ?? false
                let data = jsonObject["data"].array
                let commentModels = data?.compactMap({ return XGStatusCommentModel.deserialize(from: $0["comment"].dictionaryObject)}) ?? []
                self.isHasMoreComments = hasMore
                self.commentOffset += commentModels.count
                self.statusComments += commentModels.map({ return XGStatusCommentViewModel(statusCommentModel: $0)})
                completionHandle(true,hasMore)
            }
        }
    }
}
